package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.OrderItemMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.OrderMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.PetHealthRecordMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.PetMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Order;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.OrderItem;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Pet;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetHealthRecord;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.ExportService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
public class ExportServiceImpl implements ExportService {

    @Autowired
    private PetHealthRecordMapper healthRecordMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public String exportHealthRecords(Long petId) {
        if (petId == null) {
            return "宠物ID不能为空";
        }

        try {
            // 查询宠物信息
            Pet pet = petMapper.selectById(petId);
            if (pet == null) {
                return "宠物不存在";
            }

            // 查询健康记录
            LambdaQueryWrapper<PetHealthRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PetHealthRecord::getPetId, petId);
            wrapper.orderByDesc(PetHealthRecord::getCheckDate);
            
            List<PetHealthRecord> records = healthRecordMapper.selectList(wrapper);

            // 构建CSV内容
            StringBuilder csv = new StringBuilder();
            
            // CSV头部（BOM for Excel中文支持）
            csv.append("\uFEFF");
            csv.append("宠物健康记录导出\n");
            csv.append("宠物名称: ").append(pet.getPetName() != null ? pet.getPetName() : "").append("\n");
            csv.append("宠物品种: ").append(pet.getBreed() != null ? pet.getBreed() : "").append("\n");
            csv.append("导出时间: ").append(java.time.LocalDateTime.now().format(DATETIME_FORMATTER)).append("\n\n");

            // CSV表头
            csv.append("记录ID,检测日期,体重(kg),体温(℃),心率,呼吸频率,健康状况,症状描述,诊断结果,治疗方案,兽医姓名,下次检测日期,备注,创建时间\n");

            // CSV数据行
            for (PetHealthRecord record : records) {
                csv.append(escapeCsvField(record.getId())).append(",");
                csv.append(escapeCsvField(record.getCheckDate() != null ? 
                    record.getCheckDate().format(DATE_FORMATTER) : "")).append(",");
                csv.append(escapeCsvField(record.getWeight())).append(",");
                csv.append(escapeCsvField(record.getTemperature())).append(",");
                csv.append(escapeCsvField(record.getHeartRate())).append(",");
                csv.append(escapeCsvField(record.getRespiratoryRate())).append(",");
                csv.append(escapeCsvField(getHealthStatusText(record.getHealthStatus()))).append(",");
                csv.append(escapeCsvField(record.getSymptoms())).append(",");
                csv.append(escapeCsvField(record.getDiagnosis())).append(",");
                csv.append(escapeCsvField(record.getTreatment())).append(",");
                csv.append(escapeCsvField(record.getVeterinarian())).append(",");
                csv.append(escapeCsvField(record.getNextCheckDate() != null ? 
                    record.getNextCheckDate().format(DATE_FORMATTER) : "")).append(",");
                csv.append(escapeCsvField(record.getNotes())).append(",");
                csv.append(escapeCsvField(record.getCreateTime() != null ? 
                    record.getCreateTime().format(DATETIME_FORMATTER) : "")).append("\n");
            }

            return csv.toString();

        } catch (Exception e) {
            log.error("导出宠物健康记录失败", e);
            return "导出失败: " + e.getMessage();
        }
    }

    @Override
    public String exportOrders(Long userId) {
        try {
            // 查询订单
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            if (userId != null) {
                wrapper.eq(Order::getUserId, userId);
            }
            wrapper.orderByDesc(Order::getCreateTime);
            
            List<Order> orders = orderMapper.selectList(wrapper);

            // 构建CSV内容
            StringBuilder csv = new StringBuilder();
            
            // CSV头部（BOM for Excel中文支持）
            csv.append("\uFEFF");
            csv.append("订单列表导出\n");
            if (userId != null) {
                csv.append("用户ID: ").append(userId).append("\n");
            } else {
                csv.append("导出类型: 所有订单\n");
            }
            csv.append("导出时间: ").append(java.time.LocalDateTime.now().format(DATETIME_FORMATTER)).append("\n");
            csv.append("订单总数: ").append(orders.size()).append("\n\n");

            // CSV表头
            csv.append("订单ID,订单号,用户ID,订单总金额,实际支付金额,订单状态,支付方式,支付时间,收货地址,收货人姓名,收货人电话,发货时间,完成时间,创建时间\n");

            // CSV数据行
            for (Order order : orders) {
                csv.append(escapeCsvField(order.getId())).append(",");
                csv.append(escapeCsvField(order.getOrderNo())).append(",");
                csv.append(escapeCsvField(order.getUserId())).append(",");
                csv.append(escapeCsvField(order.getTotalAmount())).append(",");
                csv.append(escapeCsvField(order.getPaymentAmount())).append(",");
                csv.append(escapeCsvField(getOrderStatusText(order.getOrderStatus()))).append(",");
                csv.append(escapeCsvField(getPaymentMethodText(order.getPaymentMethod()))).append(",");
                csv.append(escapeCsvField(order.getPaymentTime() != null ? 
                    order.getPaymentTime().format(DATETIME_FORMATTER) : "")).append(",");
                csv.append(escapeCsvField(order.getShippingAddress())).append(",");
                csv.append(escapeCsvField(order.getReceiverName())).append(",");
                csv.append(escapeCsvField(order.getReceiverPhone())).append(",");
                csv.append(escapeCsvField(order.getShippingTime() != null ? 
                    order.getShippingTime().format(DATETIME_FORMATTER) : "")).append(",");
                csv.append(escapeCsvField(order.getCompleteTime() != null ? 
                    order.getCompleteTime().format(DATETIME_FORMATTER) : "")).append(",");
                csv.append(escapeCsvField(order.getCreateTime() != null ? 
                    order.getCreateTime().format(DATETIME_FORMATTER) : "")).append("\n");
            }

            return csv.toString();

        } catch (Exception e) {
            log.error("导出订单列表失败", e);
            return "导出失败: " + e.getMessage();
        }
    }

    /**
     * 转义CSV字段
     */
    private String escapeCsvField(Object field) {
        if (field == null) {
            return "";
        }
        String value = field.toString();
        // 如果包含逗号、引号或换行符，需要用引号包围并转义内部引号
        if (value.contains(",") || value.contains("\"") || value.contains("\n")) {
            return "\"" + value.replace("\"", "\"\"") + "\"";
        }
        return value;
    }

    /**
     * 获取健康状况文本
     */
    private String getHealthStatusText(Integer status) {
        if (status == null) {
            return "未知";
        }
        switch (status) {
            case 1:
                return "健康";
            case 2:
                return "一般";
            case 3:
                return "需要关注";
            case 4:
                return "生病";
            default:
                return "未知";
        }
    }

    /**
     * 获取订单状态文本
     */
    private String getOrderStatusText(Integer status) {
        if (status == null) {
            return "未知";
        }
        switch (status) {
            case 1:
                return "待付款";
            case 2:
                return "已付款";
            case 3:
                return "已发货";
            case 4:
                return "已完成";
            case 5:
                return "已取消";
            default:
                return "未知";
        }
    }

    /**
     * 获取支付方式文本
     */
    private String getPaymentMethodText(Integer method) {
        if (method == null) {
            return "未知";
        }
        switch (method) {
            case 1:
                return "支付宝";
            case 2:
                return "微信";
            case 3:
                return "银行卡";
            default:
                return "未知";
        }
    }
}

